package com.sky.happygos.YiPush;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

/**
 * Created by qqqqqqq on 2017/4/7.
 */

public class Proto {
    public int lenght;
    public int ver;
    public int cmd;
    public int headerLenght;
    public String header;
    public String data;

    public Proto(){

    }

    public Proto(int cmd, String header, String data){
        this.cmd = cmd;
        this.headerLenght = header.getBytes().length;
        this.lenght = data.getBytes().length;
        this.header = header;
        this.data = data;
        this.ver = 1;
    }

    public static Proto readSocket(InputStream input) throws IOException {
        Proto proto = new Proto();
        byte[] lenght = new byte[4];
        byte[] ver = new byte[1];
        byte[] cmd = new byte[1];
        byte[] headerLenght = new byte[4];
        byte[] header;
        byte[] data;

        int l = input.read(lenght);
        int v = input.read(ver);
        int c = input.read(cmd);
        int hl = input.read(headerLenght);
        header = new byte[Byte2Int.byteArrayToInt32(headerLenght)];
        int h = input.read(header);
        data = new byte[Byte2Int.byteArrayToInt32(lenght)];
        int d = input.read(data);
        proto.lenght = Byte2Int.byteArrayToInt32(lenght);
        proto.ver = Byte2Int.byteArrayToInt8(ver);
        proto.cmd = Byte2Int.byteArrayToInt8(cmd);
        proto.headerLenght = Byte2Int.byteArrayToInt32(headerLenght);
        proto.header = new String(header);
        proto.data = new String(data);
        return proto;
    }

    public void writeSocket(OutputStream out) throws IOException {
        int cap = 4+1+1+4+this.headerLenght+this.lenght;
        ByteBuffer byteBuffer = ByteBuffer.allocate(cap);
        byteBuffer.put(Byte2Int.int32ToByteArray(this.lenght));
        byteBuffer.put(Byte2Int.int8ToByteArray(this.ver));
        byteBuffer.put(Byte2Int.int8ToByteArray(this.cmd));
        byteBuffer.put(Byte2Int.int32ToByteArray(this.headerLenght));
        byteBuffer.put(this.header.getBytes());
        byteBuffer.put(this.data.getBytes());
        out.write(byteBuffer.array());
        out.flush();
    }



}
